const FIREWORK_NUM = 1
Page({
  data: {
    fireworks: [],
    cxy: {},
    canvasWidth: 0,
    canvasHeight: 0,
    timerTotal: 80,
		timerTick: 0
  },

  onLoad() {
    this.fireworks = [];
    this.ctx = wx.createCanvasContext('fireworkCanvas');
    this.setCanvasCenterXY();

    const { windowWidth, windowHeight } = wx.getSystemInfoSync();
    this.setData({
      canvasWidth: windowWidth,
      canvasHeight: windowHeight
    });

    setTimeout(() => {
      this.render();
    }, 1000);
  },

  onReady() {
    let timerTick = 0
    let timerTotal = 2
    setInterval(()=>{
      let num = FIREWORK_NUM
      console.log(timerTick,timerTotal)
      if(timerTick >= timerTotal) {
        for(var h=0;h<1;h++){
          while(num--) {
            this.createFirework()
          }
          this.setData({ "fireworks": this.fireworks })
        }
        timerTick = 0;
      } else {
        timerTick++;
      }
      // while(num--) {
      //   this.createFirework()
      // }
      this.setData({ "fireworks": this.fireworks })
    }, 2000);
  },

  setCanvasCenterXY() {
    const { windowWidth, windowHeight } = wx.getSystemInfoSync();
    this.cxy = { x: windowWidth, y: windowHeight};
  },
  calculateDistance( p1x, p1y, p2x, p2y ) {
    var xDistance = p1x - p2x,
        yDistance = p1y - p2y;
    return Math.sqrt( Math.pow( xDistance, 2 ) + Math.pow( yDistance, 2 ) );
  },
  createFirework() {
    let t_x = this.cxy.x,
        t_y = this.cxy.y;
    let target_x = Math.random( 0, t_x)*t_x,
        target_y = Math.random( 0, t_y)*t_y;
    const firework = {
      x: t_x/2,
      y: t_y/2,
      sx: t_x/2,
      sy: t_y/2,
      target_x: target_x,
      target_y: target_y,
      radius: 2,
      distanceToTarget: this.calculateDistance( t_x, t_y, target_x, target_y),
      distanceTraveled: 0,
      coordinateCount: 3,
      coordinates: [],
      color: `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`,
      fireworkParticles: [],
    };
    while( firework.coordinateCount-- ) {
      firework.coordinates.push([firework.x, firework.y]);
    }
    firework.angle = Math.atan2( firework.target_y - firework.sy, firework.target_x - firework.sx )
    firework.speed = 2
    firework.acceleration = 1.05
    firework.brightness = Math.random(80,90)
    firework.targetRadius = 1
    this.fireworks.push(firework);
    

    const createParticle = () => {
      const particle = {
        x: firework.x,
        y: firework.y,
        coordinates: [],
        coordinateCount: 5,
        radius: Math.random() * 4 + 1,
        color: firework.color,
        vx: Math.random()*10+1,
        vy: Math.random()*10+1,
        friction: 0.95,
        gravity: 1,
      };
      while( particle.coordinateCount-- ) {
        particle.coordinates.push([ particle.x, particle.y ]);
      }
      firework.fireworkParticles.push(particle);
      firework.fireworkParticles.splice(5)
    };
    for (let i = 0; i < 5; i++) {
      createParticle();
    }
  },

  render() {
    // this.ctx.clearRect(0, 0, this.data.canvasWidth, this.data.canvasHeight);
    this.fireworks.forEach((firework,idx) => {
      this.renderFirework(firework);
      this.updateFireworkParticles(firework);
      this.updateFirework(firework,idx);
    });
    this.ctx.draw();

    const canvasSelector = wx.createSelectorQuery().select('.firework-canvas');
    canvasSelector.fields({
      node: true,
      size: true
    }).exec(async (res) => {
      if (!res[0].node) {
        setTimeout(() => {
          this.render();
        }, 500);
        return;
      }

      const canvas = res[0].node;
      const canvasBoundingClientRect = res[0].node.getBoundingClientRect();
      if (canvasBoundingClientRect.height > 0 && canvasBoundingClientRect.width > 0) {
        await this.render();
      } else {
        setTimeout(() => {
          this.render();
        }, 500);
      }
    });
  },

  renderFirework(firework) {
    this.ctx.beginPath();
    this.ctx.moveTo( firework.coordinates[ firework.coordinates.length - 1][ 0 ], firework.coordinates[ firework.coordinates.length - 1][ 1 ] );
	  this.ctx.lineTo( firework.sx, firework.sy);
    this.ctx.stroke()
    // this.ctx.arc(firework.target_x, firework.target_y, firework.radius, 0, Math.PI * 2);
    // this.ctx.fillStyle = firework.color;
    // this.ctx.fill();

    firework.fireworkParticles.forEach(particle => {
      this.ctx.beginPath();
      this.ctx.rect(particle.x+firework.target_x, particle.y+firework.target_y, particle.radius, particle.radius);
      this.ctx.fillStyle = particle.color;
      this.ctx.fill();
    });
  },
  updateFirework(firework,fireworkIdx) {
      firework.coordinates.pop()
      firework.coordinates.unshift([this.x, this.y ])
      if( firework.targetRadius < 8 ) {
        firework.targetRadius += 0.3;
      } else {
        firework.targetRadius = 1;
      }
      firework.speed *= firework.acceleration;
      var vx = Math.cos( firework.angle ) * firework.speed,
			vy = Math.sin( firework.angle ) * firework.speed;
      firework.distanceTraveled = this.calculateDistance( firework.sx, firework.sy, firework.x + vx, firework.y + vy )
      if( firework.distanceTraveled >= firework.distanceToTarget ) {
        createParticles( firework.tx, firework.ty );
        // remove the firework, use the index passed into the update function to determine which to remove
        fireworks.splice( fireworkIdx, 1 );
      } else {
        // target not reached, keep traveling
        firework.x += vx;
        firework.y += vy;
      }
  },
  updateFireworkParticles(firework) {
    firework.fireworkParticles.forEach(particle => {
      particle.x += particle.vx;
      particle.y += particle.vy;
      particle.vy += particle.gravity;
    });
  },
});